package com.xwq.smartgelleryhub.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.xwq.smartgelleryhub.annotation.AuthCheck;
import com.xwq.smartgelleryhub.api.aliyunTextToImage.api.AliYunAiTextToImageApi;
import com.xwq.smartgelleryhub.api.aliyunTextToImage.model.CreateTextToImageTaskResponse;
import com.xwq.smartgelleryhub.api.aliyunTextToImage.model.GetTextToImageTaskResponse;
import com.xwq.smartgelleryhub.api.aliyunaiImageOutPaining.api.AliYunAiApi;
import com.xwq.smartgelleryhub.api.aliyunaiImageOutPaining.model.CreateOutPaintingTaskResponse;
import com.xwq.smartgelleryhub.api.aliyunaiImageOutPaining.model.GetOutPaintingTaskResponse;
import com.xwq.smartgelleryhub.api.aliyunaiReshapingImage.api.AliYunAiReshapingImageApi;
import com.xwq.smartgelleryhub.api.aliyunaiReshapingImage.model.CreateImageRestyleTaskResponse;
import com.xwq.smartgelleryhub.api.aliyunaiReshapingImage.model.GetImageRestyleTaskResponse;
import com.xwq.smartgelleryhub.api.imagesearch.so.SoImageSearchApiFacade;
import com.xwq.smartgelleryhub.api.imagesearch.so.model.SoImageSearchResult;
import com.xwq.smartgelleryhub.common.BaseResponse;
import com.xwq.smartgelleryhub.common.DeleteRequest;
import com.xwq.smartgelleryhub.common.ResultUtils;
import com.xwq.smartgelleryhub.constant.UserConstant;
import com.xwq.smartgelleryhub.exception.BusinessException;
import com.xwq.smartgelleryhub.exception.ErrorCode;
import com.xwq.smartgelleryhub.exception.ThrowUtils;
import com.xwq.smartgelleryhub.manager.auth.SpaceUserAuthManager;
import com.xwq.smartgelleryhub.manager.auth.StpKit;
import com.xwq.smartgelleryhub.manager.auth.annotation.SaSpaceCheckPermission;
import com.xwq.smartgelleryhub.manager.auth.model.SpaceUserPermissionConstant;
import com.xwq.smartgelleryhub.manager.crawlercounter.CounterManager;
import com.xwq.smartgelleryhub.model.dto.picture.*;
import com.xwq.smartgelleryhub.model.entity.Picture;
import com.xwq.smartgelleryhub.model.entity.Space;
import com.xwq.smartgelleryhub.model.entity.User;
import com.xwq.smartgelleryhub.model.enums.PictureReviewStatusEnum;
import com.xwq.smartgelleryhub.model.vo.PictureTagCategory;
import com.xwq.smartgelleryhub.model.vo.PictureVO;
import com.xwq.smartgelleryhub.service.PictureService;
import com.xwq.smartgelleryhub.service.SpaceService;
import com.xwq.smartgelleryhub.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private AliYunAiTextToImageApi aliYunAiTextToImageApi;

    @Resource
    private AliYunAiReshapingImageApi aliYunAiReshapingImageApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();

    @Resource
    private CounterManager counterManager;

    /**
     * 检测爬虫
     *
     * @param loginUserId
     */
    private void crawlerDetect(long loginUserId) {
        // 调用多少次时告警
        final int WARN_COUNT = 10;
        // 超过多少次封号
        final int BAN_COUNT = 20;
        // 拼接访问 key
        String key = String.format("user:access:%s", loginUserId);
        // 一分钟内访问次数，180 秒过期
        long count = counterManager.incrAndGetCounter(key, 1, TimeUnit.MINUTES, 180);
        // 是否封号
        if (count > BAN_COUNT) {
            // 踢下线
            StpUtil.kickout(loginUserId);
            // 封号
            User updateUser = new User();
            updateUser.setId(loginUserId);
            updateUser.setUserRole("ban");
            userService.updateById(updateUser);
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "访问太频繁，已被封号");
        }
        // 是否告警
        if (count == WARN_COUNT) {
            // 可以改为向管理员发送邮件通知
            throw new BusinessException(110, "警告访问太频繁");
        }
    }


    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(),loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（管理员）
     * @param pictureUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,HttpServletRequest request) {
        Boolean flag = pictureService.updatePicture(pictureUpdateRequest,request);
        return ResultUtils.success(flag);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间的图片，需要校验权限
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }


    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 100, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
        }

        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

//    /**
//     * 分页获取图片列表（封装类），分布式缓存redis，使用hotkey版本
//     */
//    @Deprecated
//    @PostMapping("/list/page/vo/cache")
//    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithHotKey(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
//        // 构建缓存 key（与原逻辑类似）
//        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
//        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
//        String cacheKey = "picture:listPictureVOByPage:" + hashKey;
//
//        // 判断是否为热点 key（可以通过预先统计的数据进行判断）
//        boolean isHotKey = JdHotKeyStore.isHotKey(cacheKey);
//
//        // 从本地缓存与 Redis 中按需选择获取
//        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
//        if (cachedValue != null) {
//            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
//            return ResultUtils.success(cachedPage);
//        }
//        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
//        cachedValue = valueOps.get(cacheKey);
//        if (cachedValue != null) {
//            LOCAL_CACHE.put(cacheKey, cachedValue);
//            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
//            return ResultUtils.success(cachedPage);
//        }
//
//        // 针对热点 key，可采用延长锁定时间和背景预热策略
//        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(cacheKey + ":lock", "1",
//                isHotKey ? 20 : 10, TimeUnit.SECONDS);
//        if (Boolean.TRUE.equals(lock)) {
//            try {
//                // 防止热点 key 高并发的重复查询
//                cachedValue = valueOps.get(cacheKey);
//                if (cachedValue != null) {
//                    LOCAL_CACHE.put(cacheKey, cachedValue);
//                    Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
//                    return ResultUtils.success(cachedPage);
//                }
//                // 查询数据库
//                Page<Picture> picturePage = pictureService.page(new Page<>(pictureQueryRequest.getCurrent(),
//                                pictureQueryRequest.getPageSize()),
//                        pictureService.getQueryWrapper(pictureQueryRequest));
//                Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
//
//                // 组装缓存值
//                String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
//                // 如果是热点 key，则设置较长的过期时间，并考虑异步刷新逻辑
//                int cacheExpireTime = isHotKey ? (600 + RandomUtil.randomInt(0, 300)) : (300 + RandomUtil.randomInt(0, 300));
//                valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
//                LOCAL_CACHE.put(cacheKey, cacheValue);
//
//                return ResultUtils.success(pictureVOPage);
//            } finally {
//                stringRedisTemplate.delete(cacheKey + ":lock");
//            }
//        } else {
//            try { Thread.sleep(50); } catch (InterruptedException ignored) {}
//            return listPictureVOByPageWithHotKey(pictureQueryRequest, request);
//        }
//    }


    /**
     * 分页获取图片列表（封装类），分布式缓存redis
     */
    @PostMapping("/list/page/vo/cache")
    @SentinelResource(value = "listPictureVOByPageWithCache",
            blockHandler = "handleBlockException",
            fallback = "handleFallback")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        // 普通用户默认只能查看已过审的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 构建缓存 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "picture:listPictureVOByPage:" + hashKey;

        // 从本地缓存中查询
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }

        // 从 Redis 缓存中查询
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        cachedValue = valueOps.get(cacheKey);
        if (cachedValue != null) {
            LOCAL_CACHE.put(cacheKey, cachedValue);
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }

        // 分布式锁，防止缓存击穿
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(cacheKey + ":lock", "1", 10, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(lock)) {
            try {
                // 再次检查 Redis，避免重复查询数据库
                cachedValue = valueOps.get(cacheKey);
                if (cachedValue != null) {
                    LOCAL_CACHE.put(cacheKey, cachedValue);
                    Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
                    return ResultUtils.success(cachedPage);
                }

                // 查询数据库
                Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                        pictureService.getQueryWrapper(pictureQueryRequest));
                Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);

                // 存入 Redis 缓存
                String cacheValue = JSONUtil.toJsonStr(pictureVOPage);//这里没有检查空，就算为空也存入redis解决了缓存穿透
                int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);//设置不同的过期时间解决缓存雪崩
                valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);

                // 存入本地缓存，并增加过期时间
                LOCAL_CACHE.put(cacheKey, cacheValue);

                return ResultUtils.success(pictureVOPage);
            } finally {
                stringRedisTemplate.delete(cacheKey + ":lock");
            }
        } else {
            try { Thread.sleep(50); } catch (InterruptedException ignored) {}
            return listPictureVOByPageWithCache(pictureQueryRequest, request);
        }
    }

    /**这个处理的是业务本身的异常
     * listPictureVOByPageWithCache 降级操作：直接返回本地数据或者null
     */
    public BaseResponse<Page<PictureVO>> handleFallback(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                        HttpServletRequest request, Throwable ex) {
        // 构建缓存 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "picture:listPictureVOByPage:" + hashKey;

        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 可以返回本地数据或空数据
        return ResultUtils.success(null);
    }

    /**这个方法处理所有限流以后的异常和所有熔断以后的降级异常
     * listPictureVOByPageWithCache 流控操作
     * 限流：提示“系统压力过大，请耐心等待”
     * 熔断： 执行降级操作
     */
    public BaseResponse<Page<PictureVO>> handleBlockException(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                              HttpServletRequest request, BlockException ex) {

        // 降级操作
        if (ex instanceof DegradeException) {
            return handleFallback(pictureQueryRequest, request, ex);
        }

        // 限流操作
        BaseResponse<Page<PictureVO>> response = new BaseResponse<>();
        response.setCode(ErrorCode.SYSTEM_ERROR.getCode());
        response.setMessage("系统压力过大，请耐心等待");
        response.setData(new Page<>()); // 返回空分页数据
        return response;
    }


    /**
     * 手动刷新图片列表缓存（仅管理员可调用）
     */
    @PostMapping("/cache/refresh")
    public BaseResponse<Boolean> refreshPictureCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                     HttpServletRequest request) {
        // 校验是否为管理员
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(!userService.isAdmin(loginUser),ErrorCode.NO_AUTH_ERROR);

        // 构建缓存 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "picture:listPictureVOByPage:" + hashKey;

        // 删除本地缓存
        LOCAL_CACHE.invalidate(cacheKey);

        // 删除 Redis 缓存
        Boolean deleteSuccess = stringRedisTemplate.delete(cacheKey);

        // 重新查询数据库
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        // 获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);

        // 存入 Redis 缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300); // 5 - 10 分钟随机过期
        stringRedisTemplate.opsForValue().set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);

        // 存入本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        log.info("缓存刷新成功");

        return ResultUtils.success(deleteSuccess);
    }

    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest,loginUser);
        return ResultUtils.success(true);
    }


    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList(
                "热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历",
                "风景", "动漫", "科技", "音乐", "游戏", "时尚", "旅行", "美食", "动物"
        );

        List<String> categoryList = Arrays.asList(
                "模板", "电商", "表情包", "素材", "海报",
                "摄影", "插画", "壁纸", "广告", "UI 设计", "社交媒体", "品牌", "宣传", "影视","帅哥","美女"
        );

        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 图片审核
     * @param pictureReviewRequest 图片审核请求
     * @param request http
     * @return TRUE OR FALSE
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量抓取图片
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 批量抓取图片(限流版)
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch/sentinel")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatchSentinel(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);

        // 基于 IP 限流，限制热点参数
        String remoteAddr = request.getRemoteAddr();
        Entry entry = null;
        try  {
            entry = SphU.entry("uploadPictureByBatch", EntryType.IN, 1, remoteAddr);
            // 被保护的业务逻辑
            int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
            return ResultUtils.success(uploadCount);
        } catch  (Throwable ex) {
            // 业务异常
            if (!BlockException.isBlockException(ex)) {
                Tracer.trace(ex);
                BaseResponse<Integer> response = new BaseResponse<>();
                response.setCode(ErrorCode.SYSTEM_ERROR.getCode());
                response.setMessage("系统错误");
                response.setData(null);
                return response;
            }
            // 降级操作
            if (ex instanceof DegradeException) {
                return handleFallback(pictureUploadByBatchRequest, request, ex);
            }

            // 限流操作
            BaseResponse<Integer> response = new BaseResponse<>();
            response.setCode(ErrorCode.SYSTEM_ERROR.getCode());
            response.setMessage("访问过于频繁，请稍后再试");
            response.setData(null);
            return response;
        } finally {
            if (entry != null) {
                entry.exit(1, remoteAddr);
            }
        }
    }

    /**这个处理的是业务本身的异常
     * listPictureVOByPageWithCache 降级操作：直接返回本地数据或者null
     */
    public BaseResponse<Integer> handleFallback(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                        HttpServletRequest request, Throwable ex) {
        // 可以返回本地数据或空数据
        return ResultUtils.success(null);
    }


    /**
     * 以图搜图searchPictureByPicture
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<SoImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<SoImageSearchResult> resultList = new ArrayList<>();
        // 这个 start 是控制查询多少页, 每页是 20 条
        int start = 0;
        while (resultList.size() <= 50) {
            List<SoImageSearchResult> tempList = SoImageSearchApiFacade.searchImage(
                    oldPicture.getUrl(), start
            );
            if (tempList.isEmpty()) {
                break;
            }
            resultList.addAll(tempList);
            start += tempList.size();
        }
        return ResultUtils.success(resultList);
    }

    /**
     * 颜色搜索
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 颜色搜索
     * @param searchPictureByColorRequest
     * @return
     */
    @PostMapping("/search/all_color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchAllPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        List<PictureVO> result = pictureService.searchAllPictureByColor(picColor);
        return ResultUtils.success(result);
    }


    /**
     * 批量编辑图片
     * @param pictureEditByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

    /**
     * 创建 AI 文字生成图片任务
     */
    @PostMapping("/text_to_image/create_task")
    public BaseResponse<CreateTextToImageTaskResponse> createPictureTextToImageTask(
            @RequestBody CreatePictureTextToImageTaskRequest createPictureTextToImageTaskRequest,
            HttpServletRequest request) {
        if (createPictureTextToImageTaskRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateTextToImageTaskResponse response = pictureService.createTextToImageTask(createPictureTextToImageTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 文字生成图片任务
     */
    @GetMapping("/text_to_image/get_task")
    public BaseResponse<GetTextToImageTaskResponse> getPictureTextToImageTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetTextToImageTaskResponse textToImageTask = aliYunAiTextToImageApi.getTextToImageTask(taskId);
        return ResultUtils.success(textToImageTask);
    }

    /**
     * 创建 AI 人像风格重塑任务
     */
    @PostMapping("/image_restyle/create_task")
    public BaseResponse<CreateImageRestyleTaskResponse> createImageRestyleTask(
            @RequestBody PortraitStyleRemakeRequest portraitStyleRemakeRequest,
            HttpServletRequest request) {
        if (portraitStyleRemakeRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateImageRestyleTaskResponse response = pictureService.createImageRestyleTask(portraitStyleRemakeRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 人像风格重塑任务
     */
    @GetMapping("/image_restyle/get_task")
    public BaseResponse<GetImageRestyleTaskResponse> getImageRestyleTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetImageRestyleTaskResponse imageRestyleTask = aliYunAiReshapingImageApi.getImageRestyleTask(taskId);
        return ResultUtils.success(imageRestyleTask);
    }

}
